<?php

/**
 * field actions.
 *
 * @package    cms
 * @subpackage field
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class fieldActions extends sfActions
{  
 /**
  * Executes index action
  *
  * @param sfRequest $request A request object
  */
  public function executeIndex(sfWebRequest $request, Doctrine_Query $pagerQuery = null)
  {    
    if($pagerQuery == null)
    {
      $pagerQuery = cmsFieldTable::getInstance()->getPagerQuery();
    }  
    
    $pager = new cmsPager(sfConfig::get('app_soulution_name').$request->getParameter('table'));
    
    $this->pager = $pager->setPagination($request, $pagerQuery);  
    
    $this->headers = cmsFieldTable::getInstance()->getHeadersQuery()->fetchArray();
   
    $this->rows = Cms::bindHedersWithValues($this->headers, $pager->getResults(), $request);
  }
  
   public function executeOrder(sfWebRequest $request)
  {       
    $table = $request->getParameter('table');    
       
    $moduleAttributes = $this->getUser()->getAttribute($table);
    
    $relations =  Doctrine_Core::getTable(sfConfig::get('app_soulution_name') . $table)->getRelations();
      
    $orderBy = $request->getParameter('orderBy');
        
    // pętla po wszystkich relaciach w celu wyszukania takiej która będzie zawierała jako lokalną kolumnę kolumnę z przesłanego parametru
    foreach ($relations as $relationName => $relation)
    {      
      // TODO: $orderBy != 'id' zastąpić czymś nie hardcodowany; podobnie $orderBy = 'c.' . $relationName . '.name'
      if($relation->getLocal() ==  $orderBy && $orderBy != 'id')
      {
        $orderBy = 'c.' . $relationName . '.name';
        break;
      }          
    }
    
    if(isset($moduleAttributes['orderBy']) && $moduleAttributes['orderBy'] == $orderBy . ' ASC')
    {
      $moduleAttributes['orderBy'] = $orderBy . ' DESC';      
    }
    else
    {     
      $moduleAttributes['orderBy'] = $orderBy . ' ASC';
    }      
    
    $this->getUser()->setAttribute($table, $moduleAttributes);
    
    $this->forward('field', 'index');    
  }
  
  public function executeTable_search(sfWebRequest $request)
  {       
    // pobieranie rdzennego zapytania dla modelu
    $q = cmsFieldTable::getInstance()->getPagerQuery();
    
    if($fields = $request->getParameter('fields'))
    {
      $q = cmsFieldTable::getInstance()->getWhereForSearch($fields, $q);
    }
    
    $this->executeIndex($request, $q);    
 
    // tworzenie tablicy zawierajacej wiersze tabeli oraz paginacje
    $return['rows'] = $this->getPartial('field/table_rows');    
   
    $return['pagination'] = $this->getPartial('field/pagination');   
    
    // zwracanie w postaci json do pozniejszego wykorzystania przez callback funkcji javascript
    return $this->renderText(json_encode($return));
  }    
  
  public function executeSet_position(sfWebRequest $request)
  {       
    $startPosition = ($request->getParameter('currentPage') - 1) * sfConfig::get('app_max_records_per_page'); 
    
    foreach($request->getParameter('tableOrderArray') as $key => $value)
    {
      $q = Doctrine_Query::create()
      ->update(sfConfig::get('app_soulution_name').$request->getParameter('table'))
      ->set('position', $startPosition + $key + 1)
      ->where('id = ?', $value);
      
      $q->execute();
    }    
    
    return sfView::NONE; 
  }    
  
  public function executeLucene_search(sfWebRequest $request)
  {
    $this->forwardUnless($query = $request->getParameter('query'), 'field', 'index');
    
    $this->executeIndex($request, Doctrine_Core::getTable('CmsField')->getForLuceneQuery(cmsFieldTable::getInstance()->getPagerQuery()->getSqlQuery()));

    $this->forward('field', 'index');  
  }
  
  public function executeShow(sfWebRequest $request)
  {    
    $values = cmsFieldTable::getInstance()->getPagerQuery()->where('c.id = ?', $request->getParameter('id'))->fetchArray();
       
    $headers = cmsFieldTable::getInstance()->getHeadersQuery()->fetchArray();
    
    $fields = Cms::bindHedersWithValues($headers, $values, $request);
    
    $this->fields = $fields[0];
    
    $this->forward404Unless($this->fields);
  }
  
  public function executeNew(sfWebRequest $request)
  {
    $this->form = new cmsForm();    
  }
  
  public function executeCreate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST));

    $this->form = new cmsForm(); 

    $this->processForm($request, $this->form);

    $this->setTemplate('new');
  }
  
  protected function processForm(sfWebRequest $request, sfForm $form)
  {
    $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
    if ($form->isValid())
    {
      $record = $form->save();
      
      $this->redirect($this->generateUrl('default', array('table' => $request->getParameter('table'),'action' => 'edit', 'id' => $record->getId())));
    }
  }
  
  public function executeEdit(sfWebRequest $request)
  {
    $this->forward404Unless($record = Doctrine_Core::getTable('cms' . $request->getParameter('table'))->find(array($request->getParameter('id'))), sprintf('Object cms_entry does not exist (%s).', $request->getParameter('id')));
    $this->form = new cmsForm($record);
  }
  
  public function executeUpdate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
    $this->forward404Unless($record = Doctrine_Core::getTable('cms' . $request->getParameter('table'))->find(array($request->getParameter('id'))), sprintf('Object cms_entry does not exist (%s).', $request->getParameter('id')));
    $this->form = new cmsForm($record);

    $this->processForm($request, $this->form);

    $this->setTemplate('edit');
  }

  public function executeDelete(sfWebRequest $request)
  {
    $request->checkCSRFProtection();

    $this->forward404Unless($cms_entry = Doctrine_Core::getTable('cms' . $request->getParameter('table'))->find(array($request->getParameter('id'))), sprintf('Object cms_entry does not exist (%s).', $request->getParameter('id')));
    $cms_entry->delete();

    $this->redirect('field/index');
  }
  
}
